package org.imooc.service.impl;

import org.imooc.bean.Ad;
import org.imooc.dao.AdDao;
import org.imooc.dto.AdDto;
import org.imooc.service.AdService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdServiceImpl implements AdService {

    @Autowired
    AdDao adDao;

    @Value("${adImage.savePath}")
    private String adImageSavePath;

    @Value("${adImage.url}")
    private String adImageUrl;

    @Override
    public boolean add(AdDto adDto) {
        Ad ad = new Ad();
        ad.setTitle(adDto.getTitle());
        ad.setWeight(adDto.getWeight());
        ad.setLink(adDto.getLink());

        if (adDto.getImgFile() != null && adDto.getImgFile().getSize() > 0){
            String fileName = System.currentTimeMillis() + "_"+adDto.getImgFile().getOriginalFilename();
            File file = new File(adImageSavePath + fileName);
            File fileFolder = new File(adImageSavePath);
            if (!fileFolder.exists()){
                fileFolder.mkdirs();
            }
            try {
                adDto.getImgFile().transferTo(file);
                ad.setImgFileName(fileName);
                adDao.insert(ad);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                // TODO: 2018/3/21  需要添加日志 
                return false;
            }
        }else {
            return false;
        }
    }

    @Override
    public List<AdDto> findByPage(AdDto adDto) {
        List<AdDto> adDtos = new ArrayList<>();
        Ad query = new Ad();
        BeanUtils.copyProperties(adDto, query);
        List<Ad> ads = adDao.selectByPage(query);
        for (Ad ad : ads){
            AdDto adDtoTem = new AdDto();
            adDtoTem.setImg(adImageUrl + ad.getImgFileName());
            BeanUtils.copyProperties(ad, adDtoTem);
            adDtos.add(adDtoTem);
        }
        return adDtos;
    }



    @Override
    public AdDto findById(Long id) {
        AdDto adDto = new AdDto();
        Ad ad = adDao.selectById(id);
        BeanUtils.copyProperties(ad, adDto);
        adDto.setImg(adImageUrl + ad.getImgFileName());
        return adDto;
    }

    @Override
    public boolean remove(Long id) {
        Ad ad = adDao.selectById(id);
        if (ad != null){
            int delete = adDao.delete(id);
            return delete == 1;
        }
        return true;
    }
}